import 'dart:convert';
import 'dart:io';

import 'package:base_flutter/base_flutter.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:getuiflut/getuiflut.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/ui/service_order/service_order_detail_page.dart';
import 'package:ls_work/util/speak_text_service.dart';

import '../a_yyt/home_router.dart';
import '../a_yyt/models/ge_tui_entity.dart';
import '../a_yyt/models/policy_warning_entity.dart';
import '../a_yyt/widget/policy_cell.dart';
import '../common/common.dart';
import '../net/HttpUtil.dart';
import '../net/api/http_api.dart';
import '../routers/fluro_navigator.dart';

class PushUtils {
  static Future<void> initPush(BuildContext context) async {
    String platformVersion;
    // String payloadInfo = "default";
    // String notificationState = "default";
    // Platform messages may fail, so we use a try/catch PlatformException.
    Getuiflut.initGetuiSdk;

    Getuiflut().startSdk(appId: "WlrjNZninX9au6Alq2VyT2", appKey: "ovXOALzIga9exxy7FeqKU2", appSecret: "GkK5C8UASO9pUxgtMw3kK3");
    try {
      platformVersion = await Getuiflut.platformVersion;
      print('platformVersion' + platformVersion);
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.

    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
        new FlutterLocalNotificationsPlugin();

    if(Platform.isAndroid){
      flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>()!.requestPermission();
    }

    // initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
    var initializationSettingsAndroid =
        new AndroidInitializationSettings('push');

    // var initializationSettingsIOS =
    //     IOSInitializationSettings(onDidReceiveLocalNotification: null);

    var initializationSettings = InitializationSettings(
        android: initializationSettingsAndroid,
        iOS: DarwinInitializationSettings());

    // flutterLocalNotificationsPlugin.initialize(initializationSettings,
    //     onSelectNotification: onSelectNotification);
    flutterLocalNotificationsPlugin.initialize(initializationSettings,onDidReceiveNotificationResponse: onSelectNotification);

    Getuiflut().addEventHandler(
      onWillPresentNotification: (map) async {},
      onAliasResult: (map) async {},
      onAppLinkPayload: (map) async {},
      onOpenSettingsForNotification: (map) async {},
      onPushModeResult: (map) async {},
      onQueryTagResult: (map) async {},
      onSetTagResult: (map) async {},
      onReceiveClientId: (String message) async {
        if (!TextUtil.isEmpty(message)) {
          _bindGeTuiClientId(message);
          SpUtil.putString(Constant.clientId, message);
        }
      },
      onReceiveMessageData: (Map<String, dynamic> msg) async {
        debugPrint("flutter onReceiveMessageData: $msg");

        // Toast.show('消息来了');
        ///透传
        // setState(() async {
        ///语音合成
        //await FlutterBaidutts.instance.speak('A1001，王五，请到外科第一诊室就诊' * 10);
        var str = msg['payload'].toString();
        // if(!str.contains("{")){
        //   SpeakTextService.addVoice(str);
        //   showCupertinoDialog(context: context, builder: (context){
        //     return CupertinoAlertDialog(
        //       title: Text('报警提醒',),
        //       content: Text(str,style: TextStyle(fontSize: 16,),),
        //       actions: [
        //         TextButton(onPressed: (){
        //           Navigator.pop(context);
        //           NavigatorUtils.push(context, HomeRouter.medicalPolicyPage);
        //         }, child: CommonText('前往处理'),
        //         )
        //       ],
        //     );
        //   });
        //   return;
        // }

        GeTuiInfo info = GeTuiInfo.fromJson(jsonDecode(msg['payload']));

        print('id = ${info.id}');
        var iOSPlatformChannelSpecifics =
        DarwinNotificationDetails(presentAlert: true,presentBadge: true,presentSound: true);
        var androidPlatformChannelSpecifics = AndroidNotificationDetails(
          're34dc',
          'efgf',
          channelDescription: 'erfd',
          importance: Importance.max,
          priority: Priority.high,playSound: true,
          ticker: '智慧养老院',
        );

        var platformChannelSpecifics = NotificationDetails(
          android: androidPlatformChannelSpecifics,
          iOS: iOSPlatformChannelSpecifics,
        );
        await flutterLocalNotificationsPlugin.show(
          0,
          '智慧养老院',
          info.msgBody,
          platformChannelSpecifics,
          payload: msg['payload'],
        );
        print('111id = ${info.id}');
        eventBus.fire(SendMessageEvent(100));
        // SpeakTextService.addVoice(info.msgBody);
        if (info.bizType == 1201) {
          debugPrint(jsonDecode(msg['payload']));
          Map _map = jsonDecode(msg['payload']);

          PolicyWarningInfo _info = PolicyWarningInfo.fromJson(_map['params']);
          if (_info != null) {
            //报警提醒
            showDialog(
              context: context,
              barrierDismissible: true,
              builder: (context) {
                return UnconstrainedBox(
                  constrainedAxis: Axis.horizontal,
                  child: SizedBox(
                    width: ScreenUtil.getScreenW(context),
                    child: AlertDialog(
                      content: PolicyCell(
                        type: 0,
                        callBack: () {
                          Navigator.of(context).pop();
                        },
                        info: _info,
                      ),
                    ),
                  ),
                );
              },
            );
          }
        }
        // });
      },
      onNotificationMessageArrived: (Map<String, dynamic> msg) async {
        ///消息推送
        // setState(() {
        //   _notificationState = 'Arrived';
        // });
      },
      onNotificationMessageClicked: (Map<String, dynamic> msg) async {
        // setState(() {
        //   _notificationState = 'Clicked';
        // });
      },
      onRegisterDeviceToken: (String message) async {
        // setState(() {
        //   _getDeviceToken = "$message";
        // });
      },
      onReceivePayload: (Map<String, dynamic> message) async {
        // setState(() {
        //   _onReceivePayload = "$message";
        // });
      },
      onReceiveNotificationResponse: (Map<String, dynamic> message) async {
        // setState(() {
        //   _onReceiveNotificationResponse = "$message";
        // });
      }, onTransmitUserMessageReceive: (Map<String, dynamic> event) async {  }, onGrantAuthorization: (String res) async {  }, onReceiveOnlineState: (bool res) async {  }, onLiveActivityResult: (Map<String, dynamic> event) async {  }, onRegisterPushToStartTokenResult: (Map<String, dynamic> event) async {  },
    );
  }

  static Future onSelectNotification(NotificationResponse details) async {
    var payload =  details.payload;
    if (payload != null) {
      debugPrint('notification payload1: ' + payload);
    }
    // await Navigator.push(context, new MaterialPageRoute(builder: (context) => new SecondScreen(payload)));

    var data = jsonDecode(payload!);
    if(data['bizType'].toString()=='10103'){
      var orderId = data['params']['orderId'];
      Go().push(ServiceOrderDetailPage(showDetail: false, orderId:orderId.toString()));
    }
  }

  static _bindGeTuiClientId(String clientId) {
    var map = {'cid': clientId};
    HttpUtil.instance
        .getDio()
        .post(HttpApi.geTuiClientIdBind, data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {}
      } else {}
    }).catchError((e) {
      print(e.toString());
    });
  }
}
